<?php

namespace app\admin\controller;

use \think\Controller;
use app\blog\model\LabelModel;
use app\blog\model\ArticleModel;
use app\admin\controller\Common;

/**
 * 文章控制器
 * Class Article
 * @package app\admin\controller
 */
class Article extends Controller
{
    public function lst()
    {
        return view();
    }

    /**
     * 文章新增页面
     * @return \think\response\View
     */
    public function add()
    {
        $label = LabelModel::all();
        $this->assign('label', $label);
        return view();
    }

    /**
     * 文章删除
     */
    public function article_del()
    {
        if (request()->isPost()) {
            $id = $_POST['id'];
            ArticleModel::destroy($id);
            $redis = Common::get_redis();
            $redis->del('article_' . $id);
        }
    }

    /**
     * 修改文章信息获取
     * @return \think\response\View
     */
    public function article_edit()
    {
        if (request()->isGet()) {
            $id = $_GET['id'];
            $articleModel = new ArticleModel();
            $article = $articleModel->edit_get($id);
            $labels = LabelModel::all();
            $article['md_content'] = json_decode($article['md_content']);
            $this->assign('article', $article);
            $this->assign('labels', $labels);
            return view();
        }
    }

    /**
     * 修改文章提交动作
     * @return \think\response\Json
     */
    public function edit_action()
    {
        if (!request()->isPost()) {
            $this->error('请求方式错误');
        }
        $input = $this->request->post();
        $id = $input['id'];
        $articleModel = new ArticleModel();
        $article = $articleModel->edit_get($id);
        $title = $input['title'];
        $label = '';
        $data = [];
        if (isset($input['label'])) {
            $label = $input['label'];
            $labels = array_merge($label, $article['label']);
            $label_ = array_intersect($label, $article['label']);
            $label = array_diff($labels, $label_);
            sort($label);
            $data['label'] = implode(',', $label);
        }

        $md_content = $input['content'];
        $content = $input['md-html-code'];
        // 处理特殊数据
        $md_content = json_encode($md_content);
        $content = htmlentities($content);

        $data['md_content'] = $md_content;
        $data['content'] = $content;


        $data['status'] = isset($input['status']) ?: 0;
        if ($title <> $article['title']) $data['title'] = $title;
        $res = [];

        if (count($data) <= 0) {
            return json([]);
        }
        $conn = ArticleModel::get($id);
        if (!$conn->save($data)) {
            $res['code'] = 500;
            $res['msg'] = '无更新需要';
            return json($res);
        }

        // 更改分类记录
        $labelModel = new LabelModel();
        if (!empty($label)) {
            $labelModel->where('id', 'in', $label)->setInc('article_num');
        }

        $redis = Common::get_redis();
        // 设为不展示
        if ($conn->status <> 0) {
            $id = $conn->id;
            $conn['label'] = $articleModel->get_label($conn['label']);
            $data = json_encode($conn);
            $redis->set('article_' . $id, $data);
        }else{
            $redis->del('article_'.$id);
        }
        $res['code'] = 200;
        $res['msg'] = '更新完成';

        return json($res);

    }

    /**
     * 文章列表数据接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function article_lst()
    {
        $page = input('page') ?: 1;
        $page_size = input('limit') ?: 10;
        $articleModel = new ArticleModel();
        $data = $articleModel->get_all_data($page, $page_size);
        $res['code'] = 0;
        $res['msg'] = '';
        $res['count'] = $data['total'];
        $res['data'] = $data['data'];
        return json($res);
    }

    /**
     * 新增文章动作接口
     * @return \think\response\Json
     */
    public function article_add()
    {
        if (request()->isPost()) {
            // 读参数
            $title = request()->param('title') ?: '';
            $label = $_POST['label'] ?: [];
            $md_content = $_POST['content'] ?: '';
            $content = $_POST['md-html-code'] ?: '';
            if (empty($title) || empty($label) || empty($md_content) || empty($content)) {
                return json(['msg' => '请填写内容完整']);
            }
            // 处理特殊数据
            $md_content = json_encode($md_content);
            $content = htmlentities($content);
            $status = 'status';
            if (isset($_POST[$status])) $status = $_POST['status'];
            else $status = 0;
            $label = implode(',', $label);
            // 构造字段形式的数据
            $data = array(
                'title' => $title,
                'label' => $label,
                'add_time' => date('Ymd', intval(time())),
                'click_times' => 0,
                'review' => 0,
                'status' => $status,
                'content' => $content,
                'md_content' => $md_content
            );
            $conn = new ArticleModel;
            $res = [];
            if ($conn->save($data)) {
                $res['status'] = 200;
                $res['msg'] = '添加文章成功';
                if ($conn->status <> 0) {
                    $id = $conn->id;
                    $redis = Common::get_redis();
                    $data['label'] = ArticleModel::get_label($data['label']);
                    $data = json_encode($data);
                    $redis->set('article_' . $id, $data);
                }
            } else {
                $res['status'] = 500;
                $res['msg'] = '添加文章失败';
            }
            return json($res);
        }
    }

    /**
     * 分类页面
     * @return \think\response\View
     */
    public function label()
    {
        return view();
    }

    /**
     * 分类数据接口
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function label_data()
    {
        $page = input('page') ?: 1;
        $page_size = input('page_size') ?: 10;
        $model = new LabelModel();
        $result = $model->order('id', 'desc')->paginate($page_size, '', ['page' => $page]);
        $data = $result->toArray();
        if ($result) {
            $res['code'] = 0;
            $res['msg'] = '';
            $res['count'] = $data['total'];
            $res['data'] = $data['data'];
            return json($res);
        }
    }

    /**
     * 新增分类动作
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function label_add()
    {
        if (request()->isPost()) {
            $label = $_POST['label'];
            $res = [];
            $result = LabelModel::where('label', $label)->find();
            if ($result) {
                $res['status'] = 500;
                $res['msg'] = '该标签已存在';
            } else {
                $conn = new LabelModel;
                $data['label'] = $label;
                $data['add_time'] = date("Ymd", intval(time()));
                if ($conn->save($data)) {
                    $res['status'] = 200;
                    $res['msg'] = '添加成功';
                } else {
                    $res['status'] = 500;
                    $res['msg'] = '添加失败';
                }
            }
            return json($res);
        }
    }

    /**
     * 删除分类
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function label_del()
    {
        if (request()->isPost()) {
            $id = $_POST['id'];
            $label_id = '%' . $id . '%';
            $conn = new ArticleModel;
            $res = $conn->where('label', 'like', $label_id)->find();
            $data = [];
            if ($res) {
                $data['msg'] = '该类别还在使用，删除失败';
            } else {
                $data['status'] = 200;
                LabelModel::destroy($id);
            }
            return json($data);
        }
    }
}